<template>
	<scroll-view
	 	:scroll-y="true"
		:scroll-x="false"
	 	:scroll-top="scrollTop"	 
	 	scroll-with-animation
	 	class="cate-goods cate_scroll_view"
	 	:show-scrollbar="false" 
	 >	 
		<view class="" v-for="(cate,index) in cateGoods" :key="index">
			
			<view  class="cate-title u-margin-bottom-20"
			  :class="[`cate_sub_title-${cate.id}`]" >
				<text v-if="cate.pid && cate.goods" class="font-size18 font-weight">{{cate.title}}</text>
			</view>
			
			<view class="good-items u-margin-bottom-40 "
			 v-for="(good, k) in cate.goods"  :key="k" >
				<GoodItem :item="good"></GoodItem>
			</view>
			
		</view>
	
		<up-empty v-if="cateGoods.length==0" mode="data" text="暂无门票"  icon="/static/empty/nodata.png" > </up-empty>
		
			 
		
	</scroll-view> 
</template>

<script setup>
	import GoodItem from "./good-item.vue";
	import {getGoodsByCategory} from "@/common/api.js";
	
	import {
		ref,
		reactive,
		onMounted,
		onUpdated,
		watchEffect,
		watch,
		provide,
		nextTick,
		computed
	} from 'vue';
	//定义reactive变量类似 data
	const scrollTop = ref(0);
	const isFirst = ref(true);
	const scrollViewTop = ref(0);
	const cateGoods = reactive([]);
	
	 
	 //定义属性
	const props =  defineProps({
		currentCate:{
			type: Object,
		},
		//mall页面传递过来的二级分类数组
		subcate:{
			type:Array,
		},
		//在mall页面选中的一级分类id	
		pid:{
			type: [String, Number]
		},  
	});
	 
	 
	watch(()=>props.subcate, (newValue, oldValue)=>{
		 
		fetchData()
	})
	
	//监听属性变化
	watch( ()=> props.currentCate , (newValue, oldValue)=>{		
		//计算scroll_view 滚动到top的值
		resize().then( (cate) => {	
			 
			if(cate){					
				const item =  cate.find((item)=> item.id == newValue.id) ;				
				 //当前第几个cate 
				if(item && item.rect){
					scrollTop.value =(item.rect?.top || 0 ) -( scrollViewTop.value + 20) ;
					 // console.log('移动到',scrollViewTop.value,scrollTop.value)
				}					
			}
		})	 
		
	});
	//从接口获取数据
	function fetchData(){
		isFirst.value = true;
		uni.showLoading({
			title: 'Loading'
		})
		getGoodsByCategory(props.pid).then((ret)=>{
			cateGoods.splice(0);
			cateGoods.push(...ret) ; 
			uni.hideLoading()
		})
	}
	 
	// 获取所有标签的尺寸
	function resize() {
		 // console.log('resize-function', cateGoods.value)
		// 如果不存在list，则不处理
		if(cateGoods.length === 0) {
			return new Promise((resolve)=> resolve(cateGoods));
		}
		
		return new Promise((resolve)=>{
			//第一次记录下每个分类的初始位置；
			if(isFirst.value){ 
				isFirst.value = false;
				Promise.all([getScrollViewRect(), getAllItemRect()]) .then(([viewRect,  itemRect = []]) => {	
						//scroll_view的top位置
						scrollViewTop.value = viewRect.top; 
						//每个分类的top位置
						// console.log('itemRect', itemRect)
						itemRect.map((item, index) => {	 			 
							 cateGoods[index].rect = item ;
							 // 另外计算每一个item的中心点X轴坐标
						})	
						
						resolve(cateGoods)
				})
			}else{
				 resolve(cateGoods)
			}
		})
	}
	function getScrollViewRect(){
		return new Promise(resolve => {
			queryRect("cate_scroll_view").then(size=> resolve(size) ) ;
		})
	}
	function getAllItemRect(){
		return new Promise(resolve => {
			const promiseAllArr = cateGoods.map((item, index) => queryRect(			
				`cate_sub_title-${item.id}`, true));
				
			Promise.all(promiseAllArr).then(sizes => resolve(sizes))
		})
	}
	// 获取各个标签的尺寸
	function queryRect(el, item) {	 
		return new Promise(resolve => {
			 uGetRect(`.${el}`).then(size =>  resolve(size) )
		})
		 
	} 
	function uGetRect(selector, all) {
	    return new Promise((resolve) => {
	        uni.createSelectorQuery()
	            .in(this)[all ? 'selectAll' : 'select'](selector)
	            .boundingClientRect((rect) => {
	                if (all && Array.isArray(rect) && rect.length) {
	                    resolve(rect)
	                }
	                if (!all && rect) {
	                    resolve(rect)
	                }
	            })
	            .exec()
	    })
	} 
	
</script>

<style>
</style>